<template>
  <el-upload
    class="avatar-uploader"
    :data="data"
    :action="action"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :on-error="handleError"
    :before-upload="beforeAvatarUpload">
    <img v-if="imageUrl" :src="imageUrl" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
  </el-upload>

</template>

<script>
import {getUploadToken} from "@/api/thirdservice";

export default {
  name:'index',
  data() {
    return {
      imageUrl: undefined,
      data:{
        key:'',
        OSSAccessKeyId:'',
        policy:'',
        Signature:''
      },
      action:'https://hxya-novel.oss-cn-hangzhou.aliyuncs.com/'
    };
  },
  methods: {
    handleAvatarSuccess(res, file) {
      console.log(res)
      this.imageUrl = this.action+this.data.key
      this.$emit("setImgUrl",this.imageUrl)
    },
    handleError(error,file){
      console.log(error)
    },

    beforeAvatarUpload(file) {
      if (file.type!="image/jpeg"&&file.type!="image/png"){
        this.$message.error("只能上传jpeg和png格式的文件")
        return false
      }
      if (file.size>1024*1024){
        this.$message.error("上传的文件大小不能超过1MB")
        return false
      }
      getUploadToken(file.name).then(response=>{
        const info = response.data
        this.data.key=info.key
        this.data.policy = info.key
        this.data.Signature = info.key
        this.data.OSSAccessKeyId = info.OSSAccessKeyId
        console.log(this.data)
      })
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
